import os
import socket

import paramiko
from paramiko import ServerInterface, SFTPServerInterface, SFTPServer, Transport

class MySFTPHandle(SFTPServerInterface):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def list_folder(self, path):
        try:
            return [f for f in os.listdir(path)]
        except OSError:
            return []

    def open(self, path, flags, attr):
        return os.open(path, flags)

class MySSHServer(ServerInterface):
    def check_auth_password(self, username, password):
        # 简单认证逻辑（实际使用时需替换为安全认证）
        if username == "1" and password == "1":
            return 0
        return 1

def start_sftp_server(host, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(5)

    transport = Transport(sock)
    transport.add_server_key(paramiko.RSAKey.generate(2048))
    transport.start_server(server=MySSHServer())

    channel = transport.accept()
    if channel is None:
        raise Exception("SFTP channel建立失败")

    sftp_server = SFTPServer(channel, sftp_si=MySFTPHandle)
    sftp_server.serve_forever()

if __name__ == "__main__":
    start_sftp_server("0.0.0.0", 2222)
